<?php

/* ksqurl / includes / gen.php */
/* url generation and location */
/* version 1.0.0 */
/* code.google.com/p/ksqurl */

include 'config.php';
$INSTALL_PATH = INSTALL_PATH;
$APP_NAME = APP_NAME;

class url
{
	// constructor
	function url()
	{
		// open mysql connection
$conn = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS);
if(!$conn){
  // header(s) to send
  header('HTTP/1.1 500 Internal Server Error');
  
  // html or other output to flush to browser
  die("$APP_NAME database connection error");
}
		mysql_select_db(MYSQL_DB) or die('$APP_NAME database selection error');	

	}

	// return the id for given url (or -1 if the url doesnt exist)
	function get_id($url)
	{
		$q = 'SELECT id FROM '.URL_TABLE.' WHERE (url="'.$url.'")';
		$result = mysql_query($q);
		if ($err = mysql_error()){
 			
 			###  add code to email someone the error
 			$body = 'get_id query failed' . $q . ' ' . $err;
 			###
 			

			// exit gracefully
			mysql_close($conn); 
			return -1;
 		}
 		else if ( mysql_num_rows($result) )
		{
			$row = mysql_fetch_array($result);
			return $row['id'];
			mysql_close($conn);
		}
		else
		{
			mysql_close($conn);
			return -1;
		}
	}

	// return the url for given id (or -1 if the id doesnt exist)
	function get_url($id)
	{
		$q = 'SELECT url, disabled FROM '.URL_TABLE.' WHERE (id="'.$id.'")';
		$result = mysql_query($q);
		
			if ($err = mysql_error()){
 			
 			###  add code to email someone the error
 			$body = 'get_url query failed' . $q . ' ' . $err;
			echo $body;
 			###
 			
			mysql_close($conn);
			return -1;
 		}
 		elseif ( mysql_num_rows($result) )
		{
			$row = mysql_fetch_array($result);
			if (($row['disabled']==1) && (DISABLED_URL=="")) {
				$url=INSTALL_PATH.'?disabled';
			} elseif ($row['disabled']==1) {
                                $url=DISABLED_URL;
			} else { 
				$url=$row['url']; 
			}
			return $url;
			
			mysql_close($conn);
		}
		else
		{
			mysql_close($conn);
			return -1;
		}
	}

	// add url to the database
	function add_url($url,$plain,$app='site')
	{
		// check to see if the urls already in there
		$id = $this->get_id($url);
		
		// if it is, return true
		if ( $id != -1 )
		{
			return true;
		}
		
		else // otherwise, put it in
		{
		$plain = mysql_real_escape_string(strip_tags($plain));
            	$url   = mysql_real_escape_string(strip_tags($url,"!"));
		if  ( isset($_GET['apikey'])) {
			$userid = $this->get_userid_from_apikey(mysql_real_escape_string(strip_tags($_GET['apikey'])));
			if ($userid == FALSE) { $userid = 0; }
		
		} elseif (isset($_SESSION['SESS_ID'])) {
			$userid = mysql_real_escape_string(strip_tags($_SESSION['SESS_ID']));
		} else {
			$userid = 0;
		}
			if (!empty($plain)) {
				$q = 'INSERT INTO '.URL_TABLE.' (id, url, date, createddate, text, visited, app, userid) VALUES ("'.$plain.'", "'.$url.'", NOW(), NOW(), 1, 0,"'.$app.'",'.$userid.')';
			}
			elseif (RANDOM_URLS=='1') {
	                        $id = $this->get_random_id();
                                $q = 'INSERT INTO '.URL_TABLE.' (id, url, date, createddate, visited, app, userid) VALUES ("'.$id.'", "'.$url.'", NOW(), NOW(), 0,"'.$app.'",'.$userid.')';
			}
			else {
				$id = $this->get_next_id($this->get_last_id());
				$q = 'INSERT INTO '.URL_TABLE.' (id, url, date, createddate, visited, app, userid) VALUES ("'.$id.'", "'.$url.'", NOW(), NOW(), 0,"'.$app.'",'.$userid.')';
			}
			return mysql_query($q);
			mysql_error();
			mysql_close($conn);
		}
	}

        function gen_random_id($characters, $length) {
                $string = '';
                for ($p = 0; $p < $length; $p++) {
                        $string .= $characters[mt_rand(0,( strlen($characters)-1))];
                }
                return $string;
        }

        function get_random_id()
        {

		$random_id = $this->gen_random_id(ALLOWED_CHARS,RANDOM_LENGTH);

                // check to see if the $next_id we made already exists, and if it does,
                // loop the function until we find one that doesnt
                //
                // (this is basically a failsafe to get around the potential dangers of
                //  bad use of a timestamp to pick the most recent id)
                $q = 'SELECT id FROM '.URL_TABLE.' WHERE (id="'.$random_id.'")';
                $result = mysql_query($q);
                if ($err = mysql_error()){

                        ###  add code to email someone the error
                        $body = 'get_last_id query failed' . $q . ' ' . $err;
                        ###

                        return -1;
                }
                else if ( mysql_num_rows($result) )
                {
                        $random_id = $this->get_random_id(ALLOWED_CHARS,RANDOM_LENGTH);
                }

                return $random_id;
        }

	// return most recent id (or -1 if no ids exist)
	function get_last_id()
	{	
		$q = 'SELECT id FROM '.URL_TABLE.' WHERE text = 0 ORDER BY createddate DESC LIMIT 1';
		$result = mysql_query($q);
		if ($err = mysql_error()){
 			
 			###  add code to email someone the error
 			$body = 'get_last_id query failed' . $q . ' ' . $err;
 			###
 			
			return -1;
 		}
 		else if ( mysql_num_rows($result) )
		{
			$row = mysql_fetch_array($result);
			return $row['id'];
		}
		else
		{
			return -1;
		}
	}	

	// return next id

	function get_next_id($last_id)
	{ 
	
		// if the last id is -1 (non-existant), start at the begining with 0
		if ( $last_id == -1 )
		{
			$next_id = substr(ALLOWED_CHARS,0,1);
		}
		else
		{
			// loop through the id string until we find a character to increment
			for ( $x = 1; $x <= strlen($last_id); $x++ )
			{
				$pos = strlen($last_id) - $x;

				if ( $last_id[$pos] != substr(ALLOWED_CHARS,strlen(ALLOWED_CHARS)-1,1))
				{
					$next_id = $this->increment_id($last_id, $pos);
					break; // <- kill the for loop once it finds a character
				}
			}

			// if every character was already at its max value (z),
			// append another character to the shortened string
			if ( !isSet($next_id) )
			{
				$next_id = $this->append_id($last_id);
			}
		}

		// check to see if the $next_id we made already exists, and if it does, 
		// loop the function until we find one that doesnt
		//
		// (this is basically a failsafe to get around the potential dangers of
		//  bad use of a timestamp to pick the most recent id)
		$q = 'SELECT id FROM '.URL_TABLE.' WHERE (id="'.$next_id.'")';
		$result = mysql_query($q);
		if ($err = mysql_error()){
 			
 			###  add code to email someone the error
 			$body = 'get_last_id query failed' . $q . ' ' . $err;
 			###
 			
			return -1;
 		}
 		else if ( mysql_num_rows($result) )
		{
			$next_id = $this->get_next_id($next_id);
		}

		return $next_id;
	}

	// make every character in the string 0, and then add an additional 0 to that
	function append_id($id)
	{
		for ( $x = 0; $x < strlen($id); $x++ )
		{
			$id[$x] = substr(ALLOWED_CHARS,0,1);
		}

		$id .= 0;

		return $id;
	}

	// increment a character to the next alphanumeric value and return the modified id
	function increment_id($id, $pos)
	{		
		$char = $id[$pos];
		
		$new_char = substr(ALLOWED_CHARS,strpos(ALLOWED_CHARS,$char)+1,1);

		$id[$pos] = $new_char;
		
		// set all characters after the one we're modifying to 0
		if ( $pos != (strlen($id) - 1) )
		{
			for ( $x = ($pos + 1); $x < strlen($id); $x++ )
			{
				$id[$x] = substr(ALLOWED_CHARS,0,1);
			}
		}

		return $id;
	}
        function gen_apikey($userid)
        {

                $apikey = $this->gen_random_id(ALLOWED_CHARS,'16');

                if ( $this->get_userid_from_apikey($apikey) )
                {
                        $apikey = $this->gen_apikey(ALLOWED_CHARS,'16');
                }
		$q = 'UPDATE '.USER_TABLE.' SET `apikey` = "'.$apikey.'" WHERE id = "'.$userid.'"';
                $result = mysql_query($q);
                return $apikey;
        }
        function get_userid_from_apikey($apikey)
        {
		if ($apikey=="") { return FALSE; }
                $q = 'SELECT id FROM '.USER_TABLE.' WHERE (apikey="'.$apikey.'")';
                $result = mysql_query($q);
                if ($err = mysql_error()){

                        ###  add code to email someone the error
                        $body = 'check_apikey query failed' . $q . ' ' . $err;
                        ###

                        return -1;
                }
                else if ( mysql_num_rows($result) )
                {
			$row = mysql_fetch_array($result);
                        $userid = $row['id'];
                }
		else 
		{
			$userid = FALSE;
		}

                return $userid;
        }

        function get_apikey_from_userid($userid)
        {

                $q = 'SELECT apikey FROM '.USER_TABLE.' WHERE (id="'.$userid.'")';
                $result = mysql_query($q);
		$row = mysql_fetch_array($result);

                if ($row['apikey'] != "")
                {
			$apikey = $row['apikey'];
		}
		else
		{
                        $apikey = $this->gen_apikey($userid);
                }

                return $apikey;
        }
}

function check_plain ($plain) {
	if (empty($plain)) return TRUE;
	$q = 'SELECT id FROM '.URL_TABLE.' WHERE (id="'.$plain.'")';
	$result = mysql_query($q);
	$count = mysql_num_rows($result);
	if ($count) return false;
	mysql_close($conn);
	return true;

}

function add_visits($id)
	{
		// update visits
			$updatev = 'UPDATE '.URL_TABLE.' SET visited=visited +1 WHERE id = "'.$id.'"';
			mysql_query($updatev);
			mysql_close($conn);
			
	}
function get_visits($id)
	{
		$q = 'SELECT visited FROM '.URL_TABLE.' WHERE (id="'.$id.'")';
		$result = mysql_query($q);	
		if ($err = mysql_error()){
 			
 			###  add code to email someone the error
 			$body = 'get_url query failed' . $q . ' ' . $err;
 			###
 			
			mysql_close($conn);
			return -1;
 		}
 		else if ( mysql_num_rows($result) )
		{
			$row = mysql_fetch_array($result);
			return $row['visited'];
			mysql_close($conn);
		}
		else
		{
			mysql_close($conn);
			return -1;
		}
	}
function phishtank($url)
	{
		$pturl = base64_encode($url);
		
		$URL="checkurl.phishtank.com/checkurl/";
$ch = curl_init();   
curl_setopt($ch, CURLOPT_URL,"http://$URL"); 
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "url=$pturl&format=php&app_key=".PTKEY."");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($ch);
curl_close ($ch); 
$ptdata = unserialize($result);
return $ptdata;
	}
?>
